package com.sergio.accounting.controller;

import com.sergio.accounting.dto.ApiResponse;
import com.sergio.accounting.entity.Account;
import com.sergio.accounting.service.AccountService;
import com.sergio.accounting.util.UserContextUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.math.BigDecimal;
import java.util.List;

/**
 * 账户控制器
 */
@Slf4j
@RestController
@RequestMapping("/accounts")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AccountController {

    private final AccountService accountService;

    /**
     * 获取用户的所有启用账户
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<Account>>> getUserAccounts() {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            log.info("获取账户列表 - 当前用户ID: {}", userId);
            
            if (userId == null) {
                log.error("用户未登录或JWT token无效");
                return ResponseEntity.status(401).body(ApiResponse.error("用户未登录或JWT token无效"));
            }
            
            List<Account> accounts = accountService.getUserAccounts(userId);
            log.info("获取到{}个账户", accounts.size());
            return ResponseEntity.ok(ApiResponse.success(accounts));
        } catch (Exception e) {
            log.error("获取账户列表失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("获取账户列表失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户的所有账户（包括禁用的）
     */
    @GetMapping("/all")
    public ResponseEntity<ApiResponse<List<Account>>> getAllUserAccounts() {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            log.info("获取所有账户 - 当前用户ID: {}", userId);
            
            if (userId == null) {
                log.error("用户未登录或JWT token无效");
                return ResponseEntity.status(401).body(ApiResponse.error("用户未登录或JWT token无效"));
            }
            
            List<Account> accounts = accountService.getAllUserAccounts(userId);
            log.info("获取到{}个账户（包括禁用）", accounts.size());
            return ResponseEntity.ok(ApiResponse.success(accounts));
        } catch (Exception e) {
            log.error("获取所有账户失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("获取所有账户失败: " + e.getMessage()));
        }
    }

    /**
     * 根据ID获取账户
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Account>> getAccountById(@PathVariable Long id) {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            Account account = accountService.getAccountById(id, userId);
            return ResponseEntity.ok(ApiResponse.success(account));
        } catch (Exception e) {
            log.error("获取账户详情失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取账户详情失败: " + e.getMessage()));
        }
    }

    /**
     * 创建账户
     */
    @PostMapping
    public ResponseEntity<ApiResponse<Account>> createAccount(@RequestBody Account account) {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            log.info("创建账户 - 当前用户ID: {}", userId);
            
            if (userId == null) {
                log.error("用户未登录或JWT token无效");
                return ResponseEntity.status(401).body(ApiResponse.error("用户未登录或JWT token无效"));
            }
            
            // 设置用户ID
            account.setUserId(userId);
            log.info("创建账户请求 - 账户信息: {}", account);
            
            // 手动验证必要字段
            if (account.getName() == null || account.getName().trim().isEmpty()) {
                return ResponseEntity.status(400).body(ApiResponse.error("账户名称不能为空"));
            }
            if (account.getAccountType() == null) {
                return ResponseEntity.status(400).body(ApiResponse.error("账户类型不能为空"));
            }
            
            Account createdAccount = accountService.createAccount(account);
            return ResponseEntity.ok(ApiResponse.success(createdAccount));
        } catch (Exception e) {
            log.error("创建账户失败", e);
            return ResponseEntity.status(500).body(ApiResponse.error("创建账户失败: " + e.getMessage()));
        }
    }

    /**
     * 更新账户
     */
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Account>> updateAccount(@PathVariable Long id, 
                                                            @Valid @RequestBody Account account) {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            Account updatedAccount = accountService.updateAccount(id, account, userId);
            return ResponseEntity.ok(ApiResponse.success(updatedAccount));
        } catch (Exception e) {
            log.error("更新账户失败", e);
            return ResponseEntity.ok(ApiResponse.error("更新账户失败: " + e.getMessage()));
        }
    }

    /**
     * 删除账户
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Void>> deleteAccount(@PathVariable Long id) {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            accountService.deleteAccount(id, userId);
            return ResponseEntity.ok(ApiResponse.success("删除成功", null));
        } catch (Exception e) {
            log.error("删除账户失败", e);
            return ResponseEntity.ok(ApiResponse.error("删除账户失败: " + e.getMessage()));
        }
    }

    /**
     * 启用/禁用账户
     */
    @PutMapping("/{id}/toggle")
    public ResponseEntity<ApiResponse<Account>> toggleAccountStatus(@PathVariable Long id) {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            Account account = accountService.toggleAccountStatus(id, userId);
            return ResponseEntity.ok(ApiResponse.success(account));
        } catch (Exception e) {
            log.error("切换账户状态失败", e);
            return ResponseEntity.ok(ApiResponse.error("切换账户状态失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户总资产
     */
    @GetMapping("/total-balance")
    public ResponseEntity<ApiResponse<BigDecimal>> getUserTotalBalance() {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            BigDecimal totalBalance = accountService.getUserTotalBalance(userId);
            return ResponseEntity.ok(ApiResponse.success(totalBalance));
        } catch (Exception e) {
            log.error("获取总资产失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取总资产失败: " + e.getMessage()));
        }
    }

    /**
     * 初始化用户默认账户
     */
    @PostMapping("/initialize")
    public ResponseEntity<ApiResponse<Void>> initializeDefaultAccounts() {
        try {
            Long userId = UserContextUtil.getCurrentUserId();
            accountService.initializeDefaultAccounts(userId);
            return ResponseEntity.ok(ApiResponse.success("初始化成功", null));
        } catch (Exception e) {
            log.error("初始化默认账户失败", e);
            return ResponseEntity.ok(ApiResponse.error("初始化默认账户失败: " + e.getMessage()));
        }
    }
}
